package com.example.treasureadmin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.treasureadmin.config.AliOSSConfig;
import com.example.treasureadmin.entity.MsgEntity;
import com.example.treasureadmin.mapper.GoodsMapper;
import com.example.treasureadmin.model.GoodsModel;
import com.example.treasureadmin.model.OrderModel;
import com.example.treasureadmin.util.AliOSSUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

@Service
public class GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private AliOSSConfig aliOSSConfig;
    //获取所有商品
    public List<GoodsModel> getAll(){
        QueryWrapper<GoodsModel> queryWrapper = new QueryWrapper<>();
        return goodsMapper.selectList(queryWrapper);
    }
    //根据商品名进行查询
    public GoodsModel findGoods(String name){
        QueryWrapper<GoodsModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        GoodsModel goodsModel = goodsMapper.selectOne(queryWrapper);
        if(goodsModel == null)
        {
            return null;
        }
        return goodsMapper.selectOne(queryWrapper);
    }
    //修改商品数量
    public void changeGoods(int id,String imageUrl,String name,int number,int price)
    {
        UpdateWrapper<GoodsModel> updatenumberWrapper = new UpdateWrapper<>();
        updatenumberWrapper.eq("id",id).set("image_url",imageUrl).set("name",name).set("number",number).set("price",price);
        goodsMapper.update(null,updatenumberWrapper);
    }
    //添加商品
    public void addGoods(String imageUrl,String name,int number,int price)
    {
        goodsMapper.insert(new GoodsModel(-1,imageUrl,name,number,price));
    }
    //删除商品
    public String deleteGoods(int id){
        QueryWrapper<GoodsModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        GoodsModel goodsModel = goodsMapper.selectOne(queryWrapper);
        if (goodsModel == null){
            return "101";
        }
        goodsMapper.delete(queryWrapper);
        return "200";
    }
    //上传图片
    public String uploadImage(InputStream inputStream, String suffix) {
        String fileName = RandomStringUtils.randomAlphanumeric(32).toUpperCase();
        String goodsPath = aliOSSConfig.GOODS_PATH + fileName + suffix;
        aliOSSUtils.uploadAvatar(inputStream, goodsPath);
        return aliOSSConfig.PATH+goodsPath;
    }
}
